﻿using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;
using Volo.Abp.MultiTenancy;

namespace Framework.Caching.FreeRedis
{
	/// <summary>
	/// IDistributedCacheKeyNormalizer实现类，替换默认的IDistributedCacheKeyNormalizer实现类，可用于实现更高级的键规范化
	/// </summary>
	[Dependency(ReplaceServices = true)]
	public class DistributedCacheKeyNormalizer : IDistributedCacheKeyNormalizer, ITransientDependency
	{
		protected ICurrentTenant CurrentTenant { get; }

		protected AbpDistributedCacheOptions DistributedCacheOptions { get; }

		public DistributedCacheKeyNormalizer(
			ICurrentTenant currentTenant,
			IOptions<AbpDistributedCacheOptions> distributedCacheOptions)
		{
			CurrentTenant = currentTenant;
			DistributedCacheOptions = distributedCacheOptions.Value;
		}

		public virtual string NormalizeKey(DistributedCacheKeyNormalizeArgs args)
		{
			// 缓存格式: a:appname,c:cachename,k:key
			var normalizedKey = $"a:{DistributedCacheOptions.KeyPrefix},c:{args.CacheName},k:{args.Key}";
			//var normalizedKey = $"{DistributedCacheOptions.KeyPrefix}{args.Key}";

			//if (!args.IgnoreMultiTenancy && CurrentTenant.Id.HasValue)
			//{
			//    normalizedKey = $"t:{CurrentTenant.Id.Value},{normalizedKey}";
			//}

			return normalizedKey;
		}
	}
}
